package Demo1;

public class MyCircularQueue {
    private int[] elem;
    private int front;//队头下标
    private int rear;//队尾下标
    //注意这里浪费一个空间来判断队列是否已满
    public MyCircularQueue(int k) {
    elem = new int[k];
}
    //入队
    public boolean enQueue(int value) {
        if(isFull()){
            return false;
        }
        elem[rear] = value;
        rear = (rear+1) % elem.length;
        return true;
    }
    //从队头出队
    public boolean deQueue() {
        //空的 不能出
        if(isEmpty()){
            return false;
        }
        //不空 则保存队头元素    然后front往后走
        front = (front+1)%elem.length;
        return true;
    }
    //得到队头元素
    public int Front() {
    if (isEmpty()){
        return -1;
    }
    return elem[front];
    }
    //得到队尾元素
    public int Rear() {
        if (isEmpty()){
            return -1;
        }
        //判断队尾的前一个是否合法
        int index = rear == 0 ? (elem.length-1) : (rear-1);
        return elem[index];
    }

    public boolean isEmpty() {
        return front == rear;
    }

    public boolean isFull() {
        return (rear+1) % elem.length == front;
    }
}
